package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.dongdongshop.pojo.TbPayLog;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.PayService;
import com.dongdongshop.service.SeckillService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("alipay")
@Controller
public class AliPayController {

    private static final Logger logger = LoggerFactory.getLogger(AliPayController.class);

    @Autowired
    private AlipayClient alipayClient;//获得初始化的AlipayClient

    @Autowired
    private AlipayTradePagePayRequest alipayRequest;//设置请求参数

    @Autowired
    private AlipayTradeQueryRequest alipayTradeQueryRequest;

    @Autowired
    private AlipayTradeRefundRequest alipayTradeRefundRequest;

    @Autowired
    private AlipayTradeFastpayRefundQueryRequest alipayTradeFastpayRefundQueryRequest;

    @Reference(retries = 0,timeout = 10000)
    private OrderService orderService;

    @Reference
    private PayService payService;

    @Reference(timeout = 10000,retries = 0)
    private SeckillService seckillService;

    /**
     *
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param total_amount 付款金额，必填
     * @param subject 订单名称，必填
     * @param body 商品描述，可空
     * @return
     */
    @RequestMapping("tradePagePay")
    @ResponseBody
    public String tradePagePay(String out_trade_no,String total_amount,String subject,String body) throws AlipayApiException {

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

    /**
     * 商户订单号 20209420100201
     * 支付宝交易号 2020090422001410180500898463
     * 状态TRADE_SUCCESS
     *
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号
     * @param trade_no 支付宝交易号
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("tradeQuery")
    @ResponseBody
    public String tradeQuery(String out_trade_no,String trade_no) throws AlipayApiException {

        alipayTradeQueryRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","+"\"trade_no\":\""+ trade_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayTradeQueryRequest).getBody();

        return result;
    }

    @RequestMapping("tradeRefund")
    @ResponseBody
    public String tradeRefund(String out_trade_no, String refund_amount, String out_request_no) throws AlipayApiException {

        alipayTradeRefundRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayTradeRefundRequest).getBody();
        logger.info("进入退款方法");

        // 删除数据库中订单详细表(order_item)， 根据订单详细表的id去修改订单表(order)中的实际付款金额，状态，订单的更新时间
        orderService.deleteItemOrderById(Long.parseLong(out_request_no), refund_amount);

        // 更新这个订单对应的payLog
        TbPayLog payLog = payService.getPayLogById(out_trade_no);
        // 修改支付金额
        payLog.setTotalFee(payLog.getTotalFee() - Long.parseLong(refund_amount));
        payService.updatePayLog(payLog);
        return result;
    }

    @RequestMapping("tradeRefundQuery")
    @ResponseBody
    public String tradeRefundQuery(String out_trade_no,String trade_no,String out_request_no) throws AlipayApiException {

        alipayTradeFastpayRefundQueryRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                +"\"trade_no\":\""+ trade_no +"\","
                +"\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayTradeFastpayRefundQueryRequest).getBody();

        return result;
    }

    @RequestMapping("toPaySeckill")
    @ResponseBody
    public String toPaySeckill(String out_trade_no) throws AlipayApiException {

        // 获取当前登录的用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        // 获取该母订单的信息
        TbSeckillOrder tbSeckillOrder = seckillService.getSeckillOrderById(out_trade_no);
        // 付款金额，必填
        String total_amount = String.valueOf(tbSeckillOrder.getMoney());
        // 订单名称，必填
        String subject = "ddshopSeckill" + user.getUsername();
        // 商品描述，可空
        String body = "ddshopSeckill" + user.getUsername();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
}
